import init_pkg_db

import os
import sys
import subprocess

from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
    cwd = os.path.dirname(__file__)
    task = 'update_build'
    option_list = BaseCommand.option_list + (
        make_option('-o',
            '--os_release',
            action='store',
            type='string',
            dest='os_release',
            help='designate the os release. eg. \'s11u2\' or \'s12\''),
        make_option('-b',
            '--build',
            action='store',
            type='string',
            dest='build',
            help='designate the build like \'04\' or \'16\''),
    )
    
    def get_last_build(self, current_build):
        last_build_num = int(current_build)-1
        return '0'+str(last_build_num) if last_build_num < 10 else str(last_build_num)

    def handle(self, *args, **options):
        if not options['build'] or not options['os_release']:
            sys.stderr.write('build or os_release option not given\n')
            return
        os_release = options['os_release']
        current_build = options['build']
        last_build =  self.get_last_build(current_build)
        last_file= '{0}pkg_{1}_b{2}_full.list'.format(init_pkg_db.Command.pkg_list_path, os_release, last_build)
        current_file = '{0}pkg_{1}_b{2}_full.list'.format(init_pkg_db.Command.pkg_list_path, os_release, current_build)
        p = subprocess.Popen('diff {0} {1}'.format(last_file, current_file), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if stderr:
            init_pkg_db.log(self.task, 'diff failed:' + stderr, '{0} build {1}'.format(os_release, current_build))
            return
        if stdout:
            diff
        else:
            print('packages in {0} build {1} is the same as the last build.\n'.format(os_release, current_build))
